package com.alks.entity.deserializer;

import com.alibaba.excel.util.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 自定义时间反序列化器
 *
 * @author MS
 * @since 2024/5/28下午5:58
 */
public class LocalDateTimeDeserialize extends JsonDeserializer<LocalDateTime> {
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String dateStr = parser.getValueAsString();
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        try {
            // 直接尝试按照日期时间格式解析
            return LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER);
        } catch (DateTimeParseException dateTimeParseException) {
            try {
                // 如果上面失败，尝试按照日期格式解析
                LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
                // 假设时间为当天的0点，这可能需要根据实际情况调整
                return date.atStartOfDay();
            } catch (DateTimeParseException localDateParseException) {
                // 如果两种格式都解析失败，抛出自定义异常
                throw new IllegalArgumentException("日期格式错误");
            }
        }
    }
}
